﻿<?php
header("Content-type: text/html; charset=utf-8");
require_once("../includes/public.inc.php");	
require_once("../includes/tools.class.php");
require_once("../includes/conn.php");
  
  
    /**
    * 现金红包接口
    * 2015-5-9
    * 
    * @return
    */ 
class Common_util_pub
{
      
    /**
* hbname 红包名称  fee 红包金额 /元  body 内容  openid 微信用户id
* @param $arr
* 
* @return
*/
      
public function sendhongbaoto($arr){
 $sysconfig=mysql_fetch_array(mysql_query("select cappid,cappsecret,cmchid,cdenglucode from ".DBQIAN."sys_config limit 1"));
$tools=new tools();// echo gethostbyname($_SERVER["SERVER_NAME"]);;exit;
//$comm = new Common_util_pub();
$data['mch_id'] = $sysconfig['cmchid'];
$data['mch_billno'] = $sysconfig['cmchid'].date("Ymd",time()).date("His",time()).rand(1111,9999);
$data['nonce_str'] = self::createNoncestr();
$data['re_openid'] = $arr['openid'];
$data['wxappid'] = trim($sysconfig['cappid']);
$data['nick_name'] = $arr['hbname'];
$data['send_name'] = $arr['hbname'];
$data['total_amount'] = $arr['fee']*100;
$data['min_value'] = $arr['fee']*100;
$data['max_value'] = $arr['fee']*101;
$data['total_num'] = 1;
$data['client_ip'] = $_SERVER['REMOTE_ADDR'];//'114.112.255.218';//
$data['act_name'] = '正品验证';
$data['remark'] = '该产品为正品';
$data['wishing'] = $arr['body'];
if(!$data['re_openid']) {   
     $rearr['return_msg']='缺少用户openid';
     return $rearr;
}
$data['sign'] = self::getSign($data);
$xml = self::arrayToXml($data);
//var_dump($xml);exit;
$url ="https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
$re = self::wxHttpsRequestPem($xml,$url);
	//插入数据库
	
	//$responseObj = simplexml_load_string($re);//获取xml字符串
       $rearr = self::xmlToArray($re);
       print_r($rearr);exit;//测试输出数组
	if($rearr['result_code']=="SUCCESS" && $rearr['return_code']=="SUCCESS"){
		 // print_r($rearr);
		// $utime=date("Y-m-d H:i:s",time());
		// mysql_query("update ".DBQIAN."fwm set credit=1,time=". $utime ." where fwm='".$arr['fwm']."'");
	        // mysql_query("insert into ".DBQIAN."user_xianjin(ucode,umoney,xtype,utime)values('".$arr['openid']."',".$arr['fee'].",2,".$utime.")");
		// mysql_query("update ".DBQIAN."user_list set uystate=2 where ucode='".$arr['openid']."'");
	} else {
		//print_r(self::xmlToArray($re));exit;//下面为输出错误信息
		/*Array ( [return_code] => FAIL [return_msg] => 帐号余额不足，请到商户平台充值后再重试 [result_code] => FAIL [err_code] => NOTENOUGH [err_code_des] => 帐号余额不足，请到商户平台充值后再重试 [mch_billno] => 1271621401201510221314364131 [mch_id] => 1271621401 [wxappid] => wx934cb7f852f6c585 [re_openid] => o-OMMt0_5vpsTuKKPboU_0OW-QWQ [total_amount] => 100 )
*/
		 $tools->create_file("log.txt","",$re);
		 header("Location: lingwan.php");exit;
		
	}
 
  
return  $rearr;
}
      
      
  
    function trimString($value)
    {
        $ret = null;
        if (null != $value) 
        {
            $ret = $value;
            if (strlen($ret) == 0) 
            {
                $ret = null;
            }
        }
        return $ret;
    }
      
    /**
     *  作用：产生随机字符串，不长于32位
     */
    public function createNoncestr( $length = 32 ) 
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";  
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {  
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);  
        }  
        return $str;
    }
      
    /**
     *  作用：格式化参数，签名过程需要使用
     */
    function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach($paraMap as $k => $v)
        {
            if($urlencode)
            {
               $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar;
        if (strlen($buff) > 0) 
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }
      
    /**
     *  作用：生成签名
     */
    public function getSign($Obj)
    {
	$sysconfig=mysql_fetch_array(mysql_query("select cappid,cappsecret,cappkey,cdenglucode from ".DBQIAN."sys_config limit 1"));
        foreach ($Obj as $k => $v)
        {
            $Parameters[$k] = $v;
        }
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        $String = $String."&key=".trim($sysconfig['cappkey']);//"xffwkjyxgs12315wxgzhhbxtxxb00078"; // 商户后台设置的key
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = md5($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        //echo "【result】 ".$result_."</br>";
        return $result_;
    }
      
    /**
     *  作用：array转xml
     */
public  function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
             if (is_numeric($val))
             {
                $xml.="<".$key.">".$val."</".$key.">"; 
  
             }
             else
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";  
        }
        $xml.="</xml>";
        return $xml; 
    }
      
    /**
     *  作用：将xml转为array
     */
    public function xmlToArray($xml)
    {       
        //将XML转为array        
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);      
        return $array_data;
    }
  
     public function wxHttpsRequestPem( $vars,$url, $second=30,$aHeader=array()){
          
                $ch = curl_init();
                //超时时间
                curl_setopt($ch,CURLOPT_TIMEOUT,$second);
                curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
                //这里设置代理，如果有的话
               // curl_setopt($ch,CURLOPT_PROXY, '114.112.255.218');
                //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
                curl_setopt($ch,CURLOPT_URL,$url);
                curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
                curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
   
                //以下两种方式需选择一种
   
                //第一种方法，cert 与 key 分别属于两个.pem文件
                //默认格式为PEM，可以注释dirname(__FILE__).获取文件所在层目录
               // curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
                //curl_setopt($ch,CURLOPT_SSLCERT,'./pay/apiclient_cert.pem');
                //默认格式为PEM，可以注释
               // curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
               // curl_setopt($ch,CURLOPT_SSLKEY,'./pay/apiclient_key.pem');
//   
                curl_setopt($ch,CURLOPT_CAINFO,'PEM');
                curl_setopt($ch,CURLOPT_CAINFO,dirname(__FILE__).'/pay/rootca.pem');
   
                //第二种方式，两个文件合成一个.pem文件
                curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/pay/allapiclient.pem');
   
                if( count($aHeader) >= 1 ){
                        curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
                }
   				//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
                curl_setopt($ch,CURLOPT_POST, 1);
                curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
                $data = curl_exec($ch);
           // echo  $data;exit;
                if($data){
                        curl_close($ch);
                        return $data;
                }
                else { 
                        $error = curl_errno($ch);
                        echo "call faild, errorCode:$error\n"; 
                        curl_close($ch);
                        return false;
                }
        } 
}
  
?>